<template>
  <div class="task-manager">
    <div class="filter-container">
      <el-form :model="tableParams" label-width="60">
        <el-form-item label="客户">
          <el-input placeholder="请输入" v-model="tableParams.customerName" clearable></el-input>
        </el-form-item>
        <el-form-item label="责任人">
          <el-select
            popper-class="select-user-popper"
            clearable
            v-model="userId"
            placeholder="请选择"
            @clear="clearAssignBlameUser"
            @change="changeAssignBlameUser"
          >
            <template #header>
              <div class="content-item-search">
                <el-input placeholder="请输入关键词" v-model="userKeyword" @change="searchAssignBlameUser" />
                <svg-icon iconClass="searchBox-icon" style="font-size: 24px" @click="searchAssignBlameUser" />
              </div>
            </template>
            <el-option
              v-for="userItem in assignBlameUsers"
              :key="userItem.userId"
              :v-loading="assignBlameLoading"
              :label="userItem.nickName"
              :value="userItem.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间">
          <div class="time-type">
            <el-select v-model="tableParams.dateType">
              <el-option v-for="item in timeTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-date-picker
              v-model="daterange"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </div>
        </el-form-item>
        <el-form-item label="任务名">
          <el-select popper-class="select-user-popper" v-model="searchTaskId" placeholder="请选择" @change="changeTask">
            <template #header>
              <div class="content-item-search">
                <el-input placeholder="请输入关键词" v-model="searchTask" @change="handelSearchTask" />
                <svg-icon iconClass="searchBox-icon" style="font-size: 24px" @click="handelSearchTask" />
              </div>
            </template>
            <el-option
              v-for="userItem in taskOptions"
              :key="userItem.uuid"
              :loading="isTaskLoading"
              :label="userItem.type"
              :value="userItem.uuid"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="filter-container-buttons">
        <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
        <el-button type="primary" :icon="Upload" @click="showExportDialog = true">导出</el-button>
        <el-button type="primary" plain :icon="RefreshRight" @click="handelResetFilter">重置</el-button>
      </div>
    </div>
    <div class="table-container" element-loading-text="数据加载中..." v-loading="isLoadingTable">
      <div class="table-container-tabs">
        <el-tabs v-model="tableParams.status" @tab-click="getTaskByStatus">
          <el-tab-pane :name="item.value" v-for="item in taskStatusCounts" :key="item.id">
            <template #label>
              <div>
                {{ item.label }}
                <span>({{ item.count }})</span>
              </div>
            </template>
          </el-tab-pane>
        </el-tabs>
        <div class="filter-radio" @click="changePostponeStatus">
          <svg-icon v-if="tableParams.postponeStatus === 1" iconClass="radio-icon-active" />
          <svg-icon v-else iconClass="radio-icon" />
          <div class="filter-radio-label">逾期（异常）</div>
        </div>
      </div>
      <el-table
        ref="reformTableRef"
        :data="tableData"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{ background: '#F2F6FC', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip />
        <el-table-column label="责任人" prop="userName" show-overflow-tooltip />
        <el-table-column label="关联客户" prop="customerName" show-overflow-tooltip />
        <el-table-column label="客户地址" prop="address" show-overflow-tooltip />
        <el-table-column label="计划开始日期" prop="plainStartDate" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ plainStartDate(row).value }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际开始日期" prop="factStartDate" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ factStartDate(row).value }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划完成日期" prop="plainEndDate" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ plainEndDate(row).value }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际完成日期" prop="factEndDate" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ factEndDate(row).value }}</span>
          </template>
        </el-table-column>
        <el-table-column label="任务状态" width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="state" :class="`state-${taskStateLabel(row).value[0]}`">
              {{ taskStateLabel(row).value[1] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="是否外出" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.isOut ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="delayDays" label="延期申请天数" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <template v-if="['not_start', 'ing'].includes(row.taskStatus)">
              <el-button type="primary" link style="color: #409eff" @click="handleAdjustTime(row.stageTaskId)"
                >调整计划</el-button
              >
            </template>
            <template v-if="['ing'].includes(row.taskStatus)">
              <el-button type="primary" link style="color: #409eff" @click="handelTask(row, false)">办理</el-button>
              <!--              <el-button type="primary" link style="color: #409eff" @click="handelPlanTime(row)">调整计划</el-button>-->
            </template>
            <template v-if="row.taskStatus === 'complete'">
              <el-button type="primary" link style="color: #409eff" @click="handelTask(row, true)">编辑</el-button>
              <el-button type="primary" link style="color: #409eff" @click="handelCheckStage(row)">查看</el-button>
            </template>
            <el-button v-show="row.taskStatus !== 'del'" type="primary" link style="color: #409eff" @click="handleDelete(row)"
              >删除</el-button
            >
            <el-button v-show="auditLogButton" type="primary" link style="color: #409eff" @click="handleApprovalRecord(row)"
              >审批记录</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <custom-pagination
      :total="listTotal"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      @pagination="handelPage"
    >
    </custom-pagination>

    <!--  TODO:和客户阶段办理页面/功能/组件一模一样,复制粘贴的目前没有封装   -->
    <!--  流程任务待办 start  -->
    <div class="client-stage-drawer">
      <el-drawer v-model="isShowProcessTask" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-intention">
          <title-view :title="taskInfo.taskName" />
          <div class="opt-instructions" ref="instructionsTitle">
            <el-icon><QuestionFilled /></el-icon>
            <span @click="handelShowInstructions(proxy)">操作说明</span>
            <Transition name="fade">
              <div class="instructions-container" ref="instructionsContainer" v-show="instructionsVisible">
                <div class="arrow"></div>
                <title-view title="操作说明" isClose @close="handelCloseInstructions" />
                <div class="editor-container" v-html="taskInfo.remark"></div>
              </div>
            </Transition>
          </div>
          <div class="state-forms" v-loading="formRenderLoading" element-loading-text="数据加载中...">
            <template v-if="formItemsData.length">
              <FormRender ref="formRenderRef" :forms="formItemsData" :config="formConfigData" v-model="formModelData" />
            </template>
            <!--            <template v-else>-->
            <!--              <el-empty />-->
            <!--            </template>-->
          </div>
          <!--start next-task-->
          <div class="next-task-content" v-loading="isLoadingNextTask" v-if="isShowNextTask">
            <NextTaskList v-if="nextTaskList.length" v-model="nextTaskList"></NextTaskList>
            <el-empty v-else />
          </div>
          <!--end next-task-->
          <div class="state-btns">
            <el-button style="width: 92px; background-color: #f2f3f5" @click="handelCloseForm" size="default">取消</el-button>
            <el-button
              style="width: 92px"
              v-if="(!isDisableFollowUp && formItemsData.length) || isEditTask"
              type="primary"
              @click="handelSubmitForm"
              :loading="isSubmitHandelLoading"
              :disabled="isUploadFile && isGetUploadFileUrl"
              size="default"
              >确定</el-button
            >
          </div>
        </div>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <div class="tab-content">
            <CustomTabs v-model="currentCustomIndex" :tabList="referFollowTabs" @tab-change="tabChange" />
            <el-icon :size="20" @click="handelCloseForm">
              <Close />
            </el-icon>
          </div>
          <el-timeline
            v-if="currentCustomIndex === 0"
            style="max-width: 600px"
            :hollow="true"
            :class="{ 'hide-left-line': !followUpData.length }"
          >
            <el-timeline-item v-if="!isDisableFollowUp" type="primary">
              <div class="add-follow-up" @click="handleAddFollowUp">
                <el-icon>
                  <Plus />
                </el-icon>
                <span>添加跟进</span>
              </div>
            </el-timeline-item>
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData" type="primary">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followTime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <el-empty v-else />
          </el-timeline>
          <div
            class="task-forms"
            v-if="currentCustomIndex === 1"
            v-loading="isLoadingTaskForm"
            element-loading-text="数据加载中..."
          >
            <template v-if="referenceForms.length">
              <div class="task-forms__item" v-for="item in referenceForms">
                <div class="form-title">{{ item.processModel?.formName }}</div>
                <div class="form-render">
                  <FormRender mode="DESIGN" :forms="item.processModel.formItems" :config="{}" v-model="item.data" />
                </div>
              </div>
            </template>
            <el-empty v-else />
          </div>
        </div>
      </el-drawer>
    </div>
    <!--  流程任务待办 end  -->

    <!-- 跟进任务待办 start-->
    <div class="client-follow-drawer">
      <el-drawer v-model="isFollowDrawer" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <title-view title="跟进内容" isClose @close="handelCloseFollowDrawer" />
          <el-timeline style="max-width: 600px" :hollow="true" :class="{ 'hide-left-line': !followUpData.length }">
            <el-timeline-item v-if="!isDisableFollowUp" type="primary">
              <div class="add-follow-up" @click="handleAddFollowUp">
                <el-icon>
                  <Plus />
                </el-icon>
                <span>添加跟进</span>
              </div>
            </el-timeline-item>
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData" type="primary">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followTime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <el-empty v-else />
          </el-timeline>
          <!-- <div class="state-btns">
            <el-button @click="handelCloseFollowDrawer" size="default">取消</el-button>
          </div> -->
        </div>
      </el-drawer>
    </div>
    <!-- 跟进任务待办 end-->

    <!--  客户跟进 start  -->
    <follow-dialog v-if="isShowFollow" v-model="isShowFollow" :task-info="taskInfo" @submit-after="handleSubmitFollow" />
    <!--  客户跟进 end  -->

    <!--    start导出-->
    <export-data
      :tableParams="tableParams"
      :daterange="daterange"
      v-if="showExportDialog"
      v-model="showExportDialog"
    ></export-data>
    <!--    end 导出-->
    <approval-record
      v-if="showApprovalDialog"
      v-model="showApprovalDialog"
      :currentFormParams="currentFormParams"
    ></approval-record>
    <!--    start 调整计划时间-->
    <adjust-plan-time
      v-model="showAdjustTime"
      v-if="showAdjustTime"
      fromPage="taskList"
      @adjustTimeSave="getTaskManagerList"
      :currentStageTaskId="currentStageTaskId"
    ></adjust-plan-time>
    <!--    start 调整计划时间-->
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, nextTick, toRefs, computed } from "vue";
import { dayjs } from "element-plus";
import { debounce } from "lodash";
import { Clock, Close, Plus, QuestionFilled, RefreshRight, Search, Upload } from "@element-plus/icons-vue";
import exportData from "./components/exportData.vue";
import ApprovalRecord from "./components/ApprovalRecord.vue";
import FormRender from "@/components/customComponents/formRender.vue";
import CustomTabs from "@/components/CustomTabs/index.vue";
import NextTaskList from "@/components/NextTaskList/index.vue";
import FollowDialog from "@/components/followDialog";
import AdjustPlanTime from "@/components/AdjustPlanTime/index.vue";
import requestApis from "./apis";
import { previewFormsList } from "@/apis/referenceData";
import { toDoNextTask } from "@/apis/workflow";
import { isHasFile, parseOrDefault } from "@/utils";
import { tableRowClassName } from "./utils";
import { generateId } from "@/utils/crm";
import { timeTypes, statusType } from "./config";
import defaultConfig from "@/settings";
import { dictList } from "@/apis/dict/dict";
import { useElementPosition } from "@/views/client/clientInfo/hooks/instructionsPosition";
import useComputedParams from "@/hooks/useComputedParams";
import useIsUploadFile from "@/hooks/useIsUploadFile";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

/**
 * 任务列表状态统计
 */
const taskStatusCounts = ref([...statusType]);
const handleTaskStatusCount = data => {
  const dataKeys = Object.keys(data);
  dataKeys.forEach(item => {
    const obj = taskStatusCounts.value.find(i => i.id === item);
    obj && (obj.count = data[item]);
  });
};
const getTaskStatusCount = async () => {
  const postData = { ...tableParams.value };
  postData.startDate = daterange.value?.length >= 2 ? daterange.value[0] : "";
  postData.endDate = daterange.value?.length >= 2 ? daterange.value[1] : "";
  const { data } = await requestApis.taskStatusCount(postData);
  handleTaskStatusCount(data ?? {});
};

/**
 * 任务列表
 */
const isLoadingTable = ref(false);
const initTableParams = {
  current: 1,
  size: 10,
  status: "all", // all 全部，not_start 未开始，ing 进行中，complete 已完成，del 删除
  postponeStatus: 0, //是否逾期
  customerName: "",
  userName: "",
  dateType: "2", //1.预计开始时间  2.实际开始时间 3.预计结束时间 4.实际结束时间
  startDate: "",
  endDate: "",
  taskName: ""
};
const daterange = ref([]);
const tableParams = ref({ ...initTableParams });
const tableData = ref([]);
const listTotal = ref(0);
const getTaskManagerList = async () => {
  try {
    isLoadingTable.value = true;
    const postData = { ...tableParams.value };
    postData.startDate = daterange.value?.length >= 2 ? daterange.value[0] : "";
    postData.endDate = daterange.value?.length >= 2 ? daterange.value[1] : "";
    const { data } = await requestApis.taskManagerList(postData);
    tableData.value = data?.list ?? [];
    listTotal.value = data?.total ?? 0;
    isLoadingTable.value = false;
  } catch (err) {
    isLoadingTable.value = false;
  }
};
const getTaskByStatus = e => {
  tableParams.value.current = 1;
  tableParams.value.status = statusType[e.index].value;
  tableData.value = [];
  getTaskManagerList();
};
const changePostponeStatus = () => {
  tableParams.value.postponeStatus = tableParams.value.postponeStatus === 1 ? 0 : 1;
  getTaskManagerList();
  getTaskStatusCount();
};
const handelPage = () => {
  tableData.value = [];
  getTaskManagerList();
};

/**
 * 责任人搜索
 */
const assignBlameLoading = ref(false);
const assignBlameUsers = ref([]);
const userId = ref("");
const userKeyword = ref("");
const searchAssignBlameUser = async e => {
  if (!userKeyword.value) return;
  try {
    assignBlameLoading.value = true;
    const { data } = await requestApis.searchUser({ name: userKeyword.value });
    assignBlameUsers.value = data ?? [];
    assignBlameLoading.value = false;
  } catch (err) {
    assignBlameLoading.value = false;
  }
};
const changeAssignBlameUser = e => {
  const userInfo = assignBlameUsers.value.find(item => item.userId === e);
  userInfo && (tableParams.value.userName = userInfo.nickName);
};
const clearAssignBlameUser = () => {
  tableParams.value.userName = "";
};
const handelSearch = () => {
  tableParams.value.current = 1;
  tableData.value = [];
  getTaskStatusCount();
  getTaskManagerList();
};
const handelResetFilter = () => {
  tableParams.value = {
    ...initTableParams
  };
  daterange.value = [];
  userId.value = "";
  searchTask.value = "";
  taskOptions.value = [];
  searchTaskId.value = "";
  getTaskStatusCount();
  getTaskManagerList();
};

/**
 * 任务搜索
 */
const isTaskLoading = ref(false);
const searchTask = ref("");
const searchTaskId = ref("");
const taskOptions = ref([]);
const getTaskListByTaskName = async () => {
  try {
    isTaskLoading.value = true;
    const { data } = await requestApis.exportTaskDataSearch({ keywords: searchTask.value });
    taskOptions.value =
      data?.map(item => {
        return {
          ...item,
          uuid: generateId()
        };
      }) ?? [];
    isTaskLoading.value = false;
  } catch (err) {
    console.log("getTaskListByTaskName>>>>", err);
    isTaskLoading.value = false;
  }
};
const handelSearchTask = debounce(getTaskListByTaskName, 500);
const changeTask = e => {
  const taskInfo = taskOptions.value.find(item => item.uuid === e);
  if (taskInfo) {
    tableParams.value.taskName = taskInfo.taskName;
  }
};

/**
 * 状态
 */
const taskStateLabel = useComputedParams(data => {
  return data.postponeStatus ? ["danger", "异常"] : ["primary", "正常"];
});
/**
 * 审批记录
 */
const auditLogButton = computed(() => {
  return ["audit", "refuse", "complete"].includes(tableParams.value.status);
});
/**
 * 时间
 */
const plainStartDate = useComputedParams(data => {
  return data.plainStartDate ? dayjs(data.plainStartDate).format("YYYY-MM-DD") : "";
});
const factStartDate = useComputedParams(data => {
  return data.factStartDate ? dayjs(data.factStartDate).format("YYYY-MM-DD") : "";
});
const plainEndDate = useComputedParams(data => {
  return data.plainEndDate ? dayjs(data.plainEndDate).format("YYYY-MM-DD") : "";
});
const factEndDate = useComputedParams(data => {
  return data.factEndDate ? dayjs(data.factEndDate).format("YYYY-MM-DD") : "";
});

/**
 * 提交流程任务待办
 */
const isShowProcessTask = ref(false);
const isSubmitHandelLoading = ref(false);
const handelSubmitForm = async () => {
  await nextTick();
  proxy.$refs.formRenderRef.submitForm(async data => {
    if (!data) return proxy.$modal.msgError("请完善信息");
    try {
      isSubmitHandelLoading.value = true;
      const postData = {
        deptId: userStore.userInfo.mainDeptId,
        formData: formModelData.value,
        processUsers: {},
        nextTaskList: nextTaskList.value
      };
      const { stageTaskId, commTaskId } = taskInfo.value;
      const requestApi = isEditTask.value ? requestApis.editProcessTask : requestApis.handleProcessTask;
      const paramsId = isEditTask.value ? stageTaskId : commTaskId;
      await requestApi(paramsId, postData);
      isSubmitHandelLoading.value = false;
      isShowProcessTask.value = false;
      proxy.$modal.msgSuccess("提交成功");
      getTaskManagerList();
      getTaskStatusCount();
    } catch (err) {
      isSubmitHandelLoading.value = false;
    }
  });
};
const handelCloseForm = async () => {
  if (formItemsData.value?.length) {
    await nextTick();
    proxy.$refs.formRenderRef.resetForm();
    formItemsData.value = [];
    formModelData.value = {};
  }
  followUpData.value = [];
  currentCustomIndex.value = 0;
  instructionsVisible.value = false;
  isShowProcessTask.value = false;
};
/**
 * 跟进任务待办
 */
const isFollowDrawer = ref(false);
const handelCloseFollowDrawer = () => {
  isFollowDrawer.value = false;
  followUpData.value = [];
  currentCustomIndex.value = 0;
};

/**
 * 办理/客户跟进弹窗
 */
const formRenderLoading = ref(false);
const isStateFollowLoading = ref(false);
const isEditTask = ref(false);
const isDisableFollowUp = ref(false);
// 表单
const formConfigData = ref({});
const formItemsData = ref([]);
const formModelData = ref({});
// 是否有文件上传
// TODO: 没有考虑上传失败
const { isUploadFile, isGetUploadFileUrl } = toRefs(useIsUploadFile(formItemsData, formModelData));
const getProcessModel = async requestProcessModel => {
  try {
    formRenderLoading.value = true;
    const { formId: defId, customerId, formInstanceId } = taskInfo.value;
    const { data } = await requestProcessModel(defId, customerId);
    formItemsData.value = parseOrDefault(data?.formItems, []);
    formConfigData.value = parseOrDefault(data?.formConfig, []);
    if (isDisableFollowUp.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formInstanceId && getProcessInstanceForm();
    formRenderLoading.value = false;
  } catch (err) {
    formRenderLoading.value = false;
  }
};
// 表单数据
const getProcessInstanceForm = async () => {
  const { formInstanceId } = taskInfo.value;
  const { data = {} } = await requestApis.processInstanceForm(formInstanceId);
  formModelData.value = data;
};
const getAuditAndToDoData = async () => {
  try {
    formRenderLoading.value = true;
    const { formInstanceId } = taskInfo.value;
    const { data } = await requestApis.approvalForm(formInstanceId);
    formRenderLoading.value = false;
    formConfigData.value = data?.formConfig ?? {};
    formItemsData.value = isHasFile(data?.formItems ?? [], data?.formData ?? {});
    if (isDisableFollowUp.value && !isEditTask.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formModelData.value = data?.formData || {};
  } catch (err) {
    formRenderLoading.value = false;
  }
};
// 客户信息&跟进记录
const followUpData = ref([]);
const followUpTypes = ref([]);
const getFollowUpType = async () => {
  try {
    const { data } = await dictList({ dictType: defaultConfig.dicts.FOLLER_UP_TYPE });
    followUpTypes.value = data ?? [];
  } catch (err) {
    console.log(err);
  }
};
const getClientInfoAndFollow = async customerId => {
  try {
    isStateFollowLoading.value = true;
    const { data } = await requestApis.clientInfoAndFollow(customerId);
    const crmCustomerTrackList = data?.crmCustomerTrackList || [];
    followUpData.value = crmCustomerTrackList.map(item => {
      item.roleName = `${item.roleName}  ${item.updateBy}提交于${item?.updateTime ? dayjs(item.updateTime).format("HH:mm") : ""}`;
      const followItem = followUpTypes.value.filter(subItem => subItem.dictCode === item.trackType);
      followItem && (item.trackTypeName = followItem.dictLabel);
      return item;
    });
    isStateFollowLoading.value = false;
  } catch (err) {
    isStateFollowLoading.value = false;
    console.log(err);
  }
};
const followDate = useComputedParams(time => {
  return dayjs(time).format("YYYY-MM-DD");
});
const followTime = useComputedParams(time => {
  return dayjs(time).format("hh:mm:ss");
});

/**
 * 办理/编辑人任务
 */
const taskInfo = ref({});
const handelTask = (data, statusFlag) => {
  isDisableFollowUp.value = false;
  isEditTask.value = statusFlag;
  taskInfo.value = { ...data };
  getClientInfoAndFollow(data.customerId);
  // 跟进任务
  if (data.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
    isFollowDrawer.value = true;
    return;
  }
  // 流程任务
  isShowProcessTask.value = true;
  getPreviewTaskForm();
  getToDoNextTask();
  getProcessModel(requestApis.pendingProcessModel);
};
/**
 * 任务详情
 * @param data
 */
const handelCheckStage = data => {
  isDisableFollowUp.value = true;
  isEditTask.value = false;
  taskInfo.value = { ...data };
  getClientInfoAndFollow(data.customerId);
  if (data.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
    isFollowDrawer.value = true;
    return;
  }
  isShowProcessTask.value = true;
  getPreviewTaskForm();
  data.formInstanceId && getAuditAndToDoData();
};

/**
 * 操作说明
 */
const {
  instructionsVisible,
  instructionsLeft,
  instructionsTop,
  arrowLeft,
  arrowTop,
  handelShowInstructions,
  handelCloseInstructions
} = useElementPosition();

/**
 * 客户跟进
 */
const isShowFollow = ref(false);
const handleAddFollowUp = () => {
  isShowFollow.value = true;
};
const handleSubmitFollow = () => {
  const { customerId, currentType } = taskInfo.value;
  const isFollowTask = currentType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK;
  if (isFollowTask) {
    isShowFollow.value = false;
    const message = isEditTask.value ? "操作成功" : "任务完成";
    if (isEditTask.value) {
      getClientInfoAndFollow(customerId);
    } else {
      handelCloseFollowDrawer();
    }
    proxy.$modal.msgSuccess(message);
  } else {
    getClientInfoAndFollow(customerId);
    proxy.$modal.msgSuccess("添加成功");
  }
};

/**
 * 删除任务
 */
const handleDelete = data => {
  proxy.$modal
    .confirm(`是否删除责任人${data.userName}的${data.taskName}任务？若该任务有后置任务会自动开始！`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(async () => {
      await requestApis.taskDelete(data.stageTaskId);
      getTaskManagerList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

/**
 * 审批记录
 */
const currentFormParams = ref({});
const showApprovalDialog = ref(false);
const handleApprovalRecord = data => {
  showApprovalDialog.value = true;
  currentFormParams.value = data;
};

// 导出
const showExportDialog = ref(false);
/**
 * 待办获取指派时间的下个任务
 */
const isLoadingNextTask = ref(false);
const nextTaskList = ref([]);
const isShowNextTask = computed(() => {
  return ["ing"].includes(taskInfo.value.taskStatus);
});
const getToDoNextTask = async () => {
  try {
    isLoadingNextTask.value = true;
    const { data } = await toDoNextTask(taskInfo.value.stageTaskId);
    nextTaskList.value = data?.map(item => {
      return {
        ...item,
        plainStartDate: dayjs().format("YYYY-MM-DD")
      };
    });
    isLoadingNextTask.value = false;
  } catch (err) {
    isLoadingNextTask.value = false;
    console.log(err);
  }
};

/**
 * 任务参考
 */
const currentCustomIndex = ref(0);
const referFollowTabs = ref([
  { label: "跟进记录", value: 0 },
  { label: "任务参考", value: 1 }
]);
const isLoadingTaskForm = ref(false);
const referenceForms = ref([]);
const tabChange = index => {
  index === 0 && getClientInfoAndFollow(taskInfo.value.customerId);
  index === 1 && getPreviewTaskForm();
};
const getPreviewTaskForm = async () => {
  try {
    isLoadingTaskForm.value = true;
    const { data } = await previewFormsList(taskInfo.value.stageTaskId);
    referenceForms.value =
      data?.map(item => {
        const formItems = parseOrDefault(item.processModel?.formItems, []).map(item => {
          return {
            ...item,
            props: {
              ...item.props,
              disabled: true
            }
          };
        });
        return {
          processModel: {
            ...item.processModel,
            formItems
          },
          data: item.data ?? {}
        };
      }) || [];
    isLoadingTaskForm.value = false;
  } catch (err) {
    isLoadingTaskForm.value = false;
    console.log(err);
  }
};

//调整计划
const showAdjustTime = ref(false);
const currentStageTaskId = ref("");
const handleAdjustTime = stageTaskId => {
  currentStageTaskId.value = stageTaskId;
  showAdjustTime.value = true;
};

getFollowUpType();
getTaskStatusCount();
getTaskManagerList();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
@use "taskManager";
// 操作说明
.instructions-container {
  @include mixin.flex-column;
  overflow: auto;
  position: fixed;
  left: v-bind(instructionsLeft);
  top: v-bind(instructionsTop);
  z-index: 9999;
  width: 400px;
  height: 90vh;
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;

  .arrow {
    position: fixed;
    left: v-bind(arrowLeft);
    top: v-bind(arrowTop);
    z-index: 9999;
    width: 0;
    height: 0;
    border: 14px solid transparent;
    border-left: 14px solid #fff;
  }
  .editor-container {
    flex: 1;
    width: 100%;
    overflow: auto;
  }
}
// 参考任务
.task-forms {
  position: relative;
  flex: 1;
  overflow-y: auto;
  margin-top: 20px;
  :deep(.arco-empty) {
    @include mixin.position-center;
  }
  &__item {
    .form-title {
      margin-bottom: 5px;
      font-size: 14px;
      color: #3d3d3d;
      line-height: 22px;
    }
    .form-render {
      padding: 10px;
      background: #f6f8fa;
      border: 1px solid #dcdfe6;
    }
    & + .task-forms__item {
      margin-top: 20px;
    }
  }
  :deep(.form-item-el) {
    width: 100%;
  }
}
</style>
<style lang="scss">
@use "@/assets/styles/mixin";
.select-user-popper {
  border: 1px solid #0052d9 !important;
  box-shadow: 0 0 0 2px #d9e1ff !important;
  border-radius: 3px;
  .el-select-dropdown__header {
    padding: 10px 5px 0 5px !important;
  }
  .el-scrollbar__view > .el-select-dropdown__item {
    @include mixin.flex-align;
    padding-left: 10px;
    padding-right: 10px;
    //font-size: 12px;
    color: #3d3d3d;
    line-height: 22px;
  }
  .el-popper__arrow::before {
    display: none;
  }
}
</style>
